package cn.com.smart.framework.config;

import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

import cn.com.smart.common.utils.spring.SpringUtils;
import cn.com.smart.framework.config.properties.DruidProperties;
import cn.com.smart.framework.datasource.DynamicDataSource;

/**
 * druid 配置多数据源
 * 
 */
@Configuration
public class DruidConfig
{
    @Bean(name="master")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }

    @Bean(name="slave")
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DataSource slaveDataSource(DruidProperties druidProperties)
    {
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        return druidProperties.dataSource(dataSource);
    }
    
    
  @Bean
  @Primary
  public DynamicDataSource dataSource()
  {
      Map<Object, Object> targetDataSources = new HashMap<>();
      Map<String, DataSource>  beans = SpringUtils.getBeansByType(DataSource.class);
      DataSource master = beans.get("master");
      targetDataSources.putAll(beans);
      return new DynamicDataSource(master, targetDataSources);
  }
}
